<template>
    <div class="gi_page home">
        <a-row style="margin-bottom: 16px">
            <a-col :span="24">
                <UserPanel/>
            </a-col>
        </a-row>
        <a-row class="wrapper">
            <a-col :span="24">
                <a-tabs default-active-key="1">
                    <a-tab-pane key="1" :title="'密码设置'">
                        <a-form ref="formPasswordRef" :model="form" :rules="rules" size="large" :style="{width:'600px'}">
                            <a-form-item label="新的密码" field="newPassword" required>
                                <a-input-password v-model="form.newPassword" placeholder="请输入新的密码"/>
                            </a-form-item>
                            <a-form-item label="确认密码" field="confirmPassword" required>
                                <a-input-password v-model="form.confirmPassword" placeholder="请再次确认密码"/>
                            </a-form-item>
                        </a-form>
                        <div style="width: 600px;text-align: center;margin-top: 40px">
                            <a-space>
                                <a-button>
                                    重置
                                </a-button>
                                <a-button :loading="loading" type="primary" @click="modifyPassword">
                                    立即保存
                                </a-button>
                            </a-space>
                        </div>
                    </a-tab-pane>
                    <a-tab-pane key="2" :title="'绑定手机号码'">
                        <a-form ref="formRef" :model="formPhone" :rules="phoneRule" size="large" :style="{width:'600px'}">
                            <a-form-item field="phone" label="手機號" required>
                                <a-input v-model="formPhone.phone" placeholder="请输入绑定手机号码" :max-length="11" allow-clear />
                            </a-form-item>
                            <a-form-item field="captcha"  label="验证码" required>
                                <a-input v-model="formPhone.captcha" placeholder="请输入验证码" :max-length="4" allow-clear style="flex: 1 1" />
                                <a-button
                                    class="captcha-btn"
                                    :loading="captchaLoading"
                                    :disabled="captchaDisable"
                                    size="large"
                                    @click="onCaptcha"
                                >
                                    {{ captchaBtnName }}
                                </a-button>
                            </a-form-item>
                        </a-form>

                        <div style="width: 600px;text-align: center;margin-top: 40px">
                            <a-space>
                                <a-button>
                                    重置
                                </a-button>
                                <a-button :loading="loading" type="primary" @click="modifyPhone">
                                    立即保存
                                </a-button>
                            </a-space>
                        </div>
                    </a-tab-pane>
<!--                    <a-tab-pane key="3" :title="'語言設置'">-->
                        <!--            <Certification />-->
<!--                    </a-tab-pane>-->
                </a-tabs>
            </a-col>
        </a-row>
        <Verify
            ref="VerifyRef"
            :captcha-type="captchaType"
            :mode="captchaMode"
            :img-size="{ width: '330px', height: '155px' }"
            @success="getCaptcha"
        />
    </div>
</template>

<script lang="ts" setup>
import Verify from '@/components/Verify/index.vue'
import {type FormInstance, Message, Modal} from "@arco-design/web-vue";
defineOptions({name: 'MchSetting'})
import UserPanel from './components/user-panel.vue';
import * as Regexp from "@/utils/regexp";
import {encryptByRsa} from "@/utils/encrypt";
import {updateUserPassword, updateUserPhone} from "@/apis";
import {getSmsCaptcha} from "@/apis/common/captcha";
const form = reactive({
    newPassword: '',
    confirmPassword: '',
})
const formPhone = reactive({
    phone: '',
    captcha: '',
})

const rules: FormInstance['rules'] = {
    newPassword: [{ required: true, message: '请输入新密码' }],
    confirmPassword: [{ required: true, message: '请再次输入新密码' }, {
        validator: (value, cd) => {
            return new Promise((resolve) => {
                if (value !== form.newPassword) {
                    cd('两次密码不一致')
                }
                resolve(true)
            })
        }
    }]
}
const phoneRule: FormInstance['rules'] = {
    phone: [
        { required: true, message: '请输入手机号' },
        { match: Regexp.Phone, message: '请输入正确的手机号' }
    ],
    captcha: [{ required: true, message: '请输入验证码' }]
}
const formPasswordRef = ref<FormInstance>()
const formRef = ref<FormInstance>()
const VerifyRef = ref<InstanceType<any>>()
const captchaType = ref('blockPuzzle')
const captchaMode = ref('pop')
const captchaLoading = ref(false)
// 弹出行为验证码
const onCaptcha = async () => {
    if (captchaLoading.value) return
    const isInvalid = await formRef.value?.validateField('phone')
    if (isInvalid) return
    VerifyRef.value.show()
}

const captchaTimer = ref()
const captchaTime = ref(60)
const captchaBtnName = ref('获取验证码')
const captchaDisable = ref(false)
// 重置验证码
const resetCaptcha = () => {
    window.clearInterval(captchaTimer.value)
    captchaTime.value = 60
    captchaBtnName.value = '获取验证码'
    captchaDisable.value = false
}

// 获取验证码
const getCaptcha = async () => {
    try {
        captchaLoading.value = true
        captchaBtnName.value = '发送中...'
        const res = await getSmsCaptcha({
            mobile:   encryptByRsa(formPhone.phone)
        })
        captchaLoading.value = false
        captchaDisable.value = true
        captchaBtnName.value = `获取验证码(${(captchaTime.value -= 1)}s)`
         Message.success('短信发送成功')
        //Message.success('仅提供效果演示，实际使用请查看代码取消相关注释')
        captchaTimer.value = window.setInterval(() => {
            captchaTime.value -= 1
            captchaBtnName.value = `获取验证码(${captchaTime.value}s)`
            if (captchaTime.value <= 0) {
                resetCaptcha()
            }
        }, 1000)
    } catch (error) {
        resetCaptcha()
    } finally {
        captchaLoading.value = false
    }
}

const loading = ref(false)

const modifyPassword = async () => {
    if (form.newPassword.length<1){
        Message.warning('请输入新密码')
        return;
    }
    if (form.confirmPassword.length<1){
        Message.warning('请输入确认密码')
        return;
    }
    if (form.confirmPassword != form.newPassword){
        Message.warning('兩次密码不一致')
        return;
    }
    try {
        loading.value = true
        Modal.warning({
            title: '修改密码',
            content: `是否确定修改密码？`,
            cancelText: '取消',
            okButtonProps: {status: 'danger'},
            hideCancel: false,
            draggable:true,
            maskClosable: false,
            onOk: async () => {
                const params = {
                    newPassword: form.newPassword
                }
                await updateUserPassword(params)
                form.newPassword = ''
                form.confirmPassword = '';
                Message.success('修改成功')
            },
        });
    } catch (error) {

    } finally {
        loading.value = false
    }
}

const modifyPhone = async () => {
    const isPassInvalid = await formRef.value?.validateField('phone')
    const isCaptchaInvalid = await formRef.value?.validateField('captcha')
    if (formPhone.phone.length<1){
        Message.warning('请输入电话号码')
        return;
    }
    if (formPhone.captcha.length<1){
        Message.warning('请输入收到的验证码')
        return;
    }
    try {
        loading.value = true
        Modal.warning({
            title: '修改手机号码',
            content: `是否确定修改手机号码？`,
            cancelText: '取消',
            okButtonProps: {status: 'danger'},
            hideCancel: false,
            draggable:true,
            maskClosable: false,
            onOk: async () => {
                const params = {
                    mobile: formPhone.phone,
                    verifyCode: formPhone.captcha
                }
                await updateUserPhone(params)
                formPhone.phone = ''
                formPhone.captcha = '';
                Message.success('修改成功')
            },
        });
    } catch (error) {

    } finally {
        loading.value = false
    }
}
</script>

<style scoped lang="less">
.container {
    padding: 0 20px 20px 20px;
}

.wrapper {
    padding: 20px 0 0 20px;
    min-height: 500px;
    background-color: var(--color-bg-2);
    border-radius: 4px;
    margin-bottom: 200px;
}

:deep(.section-title) {
    margin-top: 0;
    margin-bottom: 16px;
    font-size: 14px;
}

.actions {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    height: 60px;
    padding: 14px 20px 14px 0;
    background: var(--color-bg-2);
    text-align: right;
}

.captcha-btn {
    height: 40px;
    margin-left: 12px;
    min-width: 98px;
    border-radius: 4px;
}

.btn {
    height: 40px;
}
</style>
